//logs.js
var app = getApp();
import Api from '../../../api/api.js';
import Util from '../../../utils/util.js';

const api = new Api();
Page({
  data: {
    postDetail: {},
    dataDetail: {},
    connentList: [],
    showShare: false,
    userId: '',
    postId: '',
    isNeedFresh:false,
    bangFuDict:null,
    zhongCaoDict:null,
    votesList:null,
    isVoted:false,
    totalVotes:0,
    votedIndex:-1,
    backContentList:null,
    isAuthorization: false,
  },
  onLoad: function(options) {
    this.data.userId = options.USER_ID;
    this.data.postId = options.POST_ID;
    var scene = decodeURIComponent(options.scene);
    if (scene && scene != 'undefined') {
      this.data.postId = scene;
    }
    
    this.getUserData();
    wx.removeStorageSync("canvasData");
  },
  onShow(){
    if (this.data.isNeedFresh){
      this.data.isNeedFresh = false;
      this.getDetailData();
    }

  },
  getDetailData() {
    var _this = this;
    var map = {};
    map.id = this.data.postId;
    map.userId = app.USER_ID();
    this.data.totalVotes = 0;
    this.data.votedIndex = -1;
      this.data.isVoted = false;
    api.getRequestData(app.postDetailtUrl, map, false, "GET").then(res => {
      if (res.data.errorCode == 0) {
        var dict = res.data.model.post;
        console.log(JSON.stringify(res.data.model));
        var productId = res.data.model.post.productId;
        if (productId){
          productId = productId+"";
          if (productId.length > 0){
            var skuId =  res.data.model.post.skuId;
            _this.getGoodDetail(productId,skuId);
          }
        }
        var imgs = JSON.parse(dict.imgs);
        dict.imgs = imgs;
        var content = dict.content;
        var contents = content.split("#");
        dict.contents = contents;
        _this.setData({
          connentList: res.data.model.commentList,
          dataDetail: res.data.model,
          postDetail: dict
        });
        var bangFuDict = res.data.model.bases;
        if (bangFuDict){
          _this.setData({
            bangFuDict:bangFuDict
          });
        }
        if (dict.backPublish == 1){
          var backContentList = dict.backContent;
          if (backContentList) {
            backContentList = JSON.parse(backContentList);
            _this.setData({
              backContentList: backContentList
            });
          }
        }
        var votesList = res.data.model.votes;
        if (votesList){
          for (var i = 0; i < votesList.length;i++){
            var item = votesList[i];
            if (item.voteUser){
              _this.setData({
                votedIndex:i,
                isVoted:true
              });
            }
            var qty = parseInt(item.vote.voteQty+"");
            _this.data.totalVotes += qty;
          }
          for (var i = 0; i < votesList.length; i++) {
            var item = votesList[i];
            var qty = parseFloat(item.vote.voteQty + "") * 1.00;
            item.percent = 100.00 * qty / _this.data.totalVotes;
          }
          _this.setData({
            totalVotes: _this.data.totalVotes,
            votesList: votesList
          });
        }
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  getGoodDetail(productId,skuId) {
    var _this = this;
    var map = {};
    map.productId = productId;
    api.getRequestData(app.goodsDetailUrl, map, true, "GET").then(res => {
      if (res.data.errorCode == 0) {
        var list = res.data.model.skus;
        var skuDict = null;
        for(var i = 0;i < list.length;i++){
          var dict = list[i];
          if (dict.id == skuId){
            skuDict = dict;
            break;
          }
        }
       _this.setData({
         zhongCaoDict: skuDict
       });
      } 
    });
  },
  getTimeDate(time) {
    time = time.replace("T", ' ');
    time = time.substring(0, 19);
    return time;
  },
  shareItemClick() {
    this.setData({
      showShare: true
    });
  },
  hideShareClickView() {
    this.setData({
      showShare: false
    });
  },
  agreeClick(e){
    var index = parseInt(e.currentTarget.dataset.key);
    var dict = this.data.connentList[index];
    var com_id = dict.comment.id;
    var isAgree = dict.comment.isAgree;
    var userId = app.USER_ID();
    this.agreeUpdate(com_id, userId,isAgree);

  },
  replayAgreeClick(e){
    var key = e.currentTarget.dataset.key;
    var array = key.split("_");
    var index = parseInt(array[0]);
    var dict = this.data.connentList[index];
    var arr = dict.reply;
    var idx = parseInt(array[1]);
    var dic = arr[idx];
    var isAgree = dic.isAgree;
    var userId = app.USER_ID();
    var com_id = dic.id;
    this.agreeUpdate(com_id, userId, isAgree);
  },
  agreeUpdate(id, user_id, isAgree){
    var _this = this;
    var map = {};
    map.commentId = id;
    map.userId = user_id;
    api.getRequestData(app.commonAgreUrl, map, false, "POST").then(res => {
      if (res.data.errorCode == 0) {
        if (isAgree){
          app.alert("取消赞成功～");
        } else {
          app.alert("点赞成功～");
        }
        setTimeout(function () {
          _this.getDetailData();
        }, 1000);
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });

  },
  postAgreeClick(){
    var _this = this;
    var map = {};
    map.postId = this.data.postId;
    map.userId = app.USER_ID();

    api.getRequestData(app.postAgreeUrl, map, false, "POST").then(res => {
      if (res.data.errorCode == 0) {
        app.alert("操作成功～");
        setTimeout(function () {
          _this.getDetailData();
        }, 1000);
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });

  },
  moreEvaluateClick(){
    var path = "/pages/index/evaluate/moreEvaluete?id=" + this.data.postId + "&contentType=5";
    wx.navigateTo({
      url: path,
    })
  },
  goToDaShang() {
    wx.navigateTo({
      url: '/pages/index/dashang/dashang?contentId='+this.data.postId,
    })
  },
  goToBangFu() {
    app.ORDER_TYPE = "6";
    app.BASE_ID = this.data.bangFuDict.basesId;
    wx.navigateTo({
      url: '/pages/index/bfProducts/bfProducts?postId='+this.data.postId,
    })
  },
  goToGoodDetail(){
    app.ORDER_TYPE = "5";
    wx.navigateTo({
      url: '/pages/index/goodsDetail/goodsDetail?postId='+this.data.postId + "&productId=" + this.data.zhongCaoDict.productId,
    })
  },
  replayEvaluate(e){
    var parentCommentId = e.currentTarget.dataset.key;
    var path = "/pages/index/evaluate/evaluate?id=" + this.data.postId + "&contentType=5" + "&parentCommentId=" + parentCommentId;
    wx.navigateTo({
      url: path,
    })
  },
  goToEvaluate() {
    var path = "/pages/index/evaluate/evaluate?id=" + this.data.postId + "&contentType=5" + "&parentCommentId=0";
    wx.navigateTo({
      url: path,
    })
  },
  onShareAppMessage: function () {
    this.sharePost();
    var titleText = "";
    if (this.data.postDetail.title) {
      if (this.data.postDetail.title.length > 0){
        titleText = '【'+this.data.postDetail.title+'】'
      }
    }
    var text0 = this.data.postDetail.contents[0];
    var text1 = '';
    if (this.data.postDetail.contents[1]){
      if (this.data.postDetail.contents[1].length > 0){
        text1 = '#'+this.data.postDetail.contents[1]+'#'
      }
    }
    var text2 = '';
    if (this.data.postDetail.contents[2]){
      text2 = this.data.postDetail.contents[2];
    }
    var title = titleText + text0 + text1 + text2;
    return {
      title: title,
      desc: title,
      path: "/pages/index/detail/detail?POST_ID=" + this.data.postId
    }
  },
  sharePost(){
    var _this = this;
    var map = {};
    map.id = this.data.postId;
    api.getRequestData(app.postShareUrl, map, false, "GET").then(res => {
      if (res.data.errorCode == 0) {
        app.HOMENEEDFRESH = true;
        setTimeout(function(){
          _this.getDetailData();
       },1400);
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  previewImageClick(e){
    var index = e.currentTarget.dataset.key;
    var list = this.data.postDetail.imgs;
    var url = list[index];
    wx.previewImage({
      urls: list,
      current: url
    })
  },
  previewImageTWClick(e){
    var url = e.currentTarget.dataset.key;
    wx.previewImage({
      urls: [url],
      current: url
    })
  },
  zhichiClick(e){
    var _this = this;
    var id = e.currentTarget.dataset.key;
    var map = {};
    map.userId = app.USER_ID();
    map.postId = this.data.postId;
    map.postVoteId = id;

    api.getRequestData(app.voteSaveUrl, map, false, "POST").then(res => {
      if (res.data.errorCode == 0) {
        app.alert("投票成功~");
        _this.setData({
          isVoted: true
        });
        setTimeout(function(){
           _this.getDetailData();
        },1400);
      } else {
        app.alert(res.data.errorMsg);
      }
    });
  },
  goToVoteDetial(e) {
    var id = e.currentTarget.dataset.key;
    wx.navigateTo({
      url: '/pages/index/huaTiList/postList?topicId=' + id,
    })
  },
  followClick() {
    var _this = this;
    var map = {};
    map.fanUserId = app.USER_ID();
    map.type = "5";
    if (app.USER_ID() == this.data.postDetail.userId) {
      app.alert("不能关注自己呀~");
      return;
    }
    map.userId = this.data.postDetail.userId;

    api.getRequestData(app.userFansSaveUrl, map, false, "POST").then(res => {
      if (res.data.errorCode == 0) {
        app.showToasts("关注成功~");
        app.HOMENEEDFRESH = true;
        _this.data.dataDetail.isFans = 1;
        _this.setData({
          dataDetail: _this.data.dataDetail
        });
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  canFollow() {
    var _this = this;
    wx.showModal({
      title: '提示',
      content: '确定不在关注?',
      confirmText: '确定',
      confirmColor: '#E97D6B',
      success: function (res) {
        if (res.confirm) {
          _this.cancelFollow();
        } else if (res.cancel) {
        }
      }
    });
  },
  cancelFollow() {
    var _this = this;
    var map = {};
    map.userId = app.USER_ID();
    map.userId2 = this.data.postDetail.userId;
    api.getRequestData(app.deleteUserFansByUserId, map, false, "GET").then(res => {
      if (res.data.errorCode == 0) {
        app.alert("取消关注成功~");
        app.HOMENEEDFRESH = true;
        _this.data.dataDetail.isFans = 0;
        _this.setData({
          dataDetail: _this.data.dataDetail
        });
      } else {
        wx.showToast({
          title: res.data.errorMsg,
          icon: 'none',
          duration: 1500
        });
      }
    });
  },
  getUserData() {
    var _this = this;
    app.getNewUserData().then(res => {
      _this.setData({
        isAuthorization: res
      });
      if (!res) {
        _this.getDetailPageData();
      }
    });
  },
  getDetailPageData(){
    var _this = this;
    app.getOpenIdData().then(res => {
      _this.getDetailData();
    });
  },
  // 获取用户信息
  getNewUserInfo(e) {
    var _this = this;
    app.getNewUserData().then(res => {
      _this.setData({
        isAuthorization: res
      });
      if (!res) {
        _this.getDetailPageData();
      }

    });
  },
  // 开始生成海报
  saveCanvasClick(){
    this.sharePost();
    this.setData({
      showShare: false
    });
    var stirng = JSON.stringify(this.data.dataDetail);
    wx.setStorageSync("canvasData", stirng);
    wx.navigateTo({
      url: '/pages/index/canvas/canvas',
    })
  },
  loolUserPostList(e){
    var userId = e.currentTarget.dataset.key;
    wx.navigateTo({
      url: '/pages/mine/otherDetail/otherDetail?authorUserId='  + userId,
    })
  },
})